package com.david.mydemo.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
public class EasyExcelUtil {

    private static final String FILE_SUFFIX = ".xlsx";

    /**
     * 导出excel
     * @param response
     * @param fileName  文件名
     * @param sheetName sheet名
     * @param list      数据 list为空返回 空Excel
     */
    public static void export(HttpServletResponse response, String fileName, String sheetName, List<?> list, Class<?> zlass) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileNameCode = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameCode + FILE_SUFFIX);
        EasyExcel.write(response.getOutputStream(), zlass)
                .sheet(sheetName).doWrite(list);
    }

    /**
     * excel导出 批注
     * @param response
     * @param fileName 文件名
     * @param list 导出数据
     * @param writeHandler 批注拦截器
     */
    public static void export(HttpServletResponse response, String fileName,
                              List list, WriteHandler writeHandler, Class zlass) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileNameCode = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameCode + FILE_SUFFIX);
        EasyExcel.write(response.getOutputStream(), zlass)
                .inMemory(Boolean.TRUE).registerWriteHandler(writeHandler)
                .sheet(fileName).doWrite(list);
    }



    /**
     * 导出Excel
     * @param response
     * @param fileName 文件名
     * @param list 导出数据
     * @return void
     */
    public static void export(HttpServletResponse response, String fileName, List<?> list, Class<?> zlass) throws Exception {
        export(response, fileName, fileName, list, zlass);
    }

    /**
     * 读取excel文件
     * @param file 文件
     * @param clazz 模板类
     * @return java.util.List
     */
    public  static <T> List<T> read(MultipartFile file, Class<T> clazz) {
        try {
            return EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(clazz).sheet()
                    .doReadSync();
        } catch (IOException e) {
            log.error("读取excel文件报错", e);
        }
        return null;
    }

    public static List<LinkedHashMap<Integer, Object>> readExcel(InputStream inputStream) {
        return EasyExcel.read(inputStream).headRowNumber(0).autoCloseStream(true).doReadAllSync();
    }

    public static List<LinkedHashMap<Integer, Object>> readExcel(InputStream inputStream, String sheetName) {
        return EasyExcel.read(inputStream).headRowNumber(0).autoCloseStream(true).sheet(sheetName).doReadSync();
    }

    public static List<LinkedHashMap<Integer, Object>> readExcel(InputStream inputStream, Integer sheetIndex) {
        return EasyExcel.read(inputStream).headRowNumber(0).autoCloseStream(true).sheet(sheetIndex).doReadSync();
    }

    public static Map<String, List<LinkedHashMap<Integer, Object>>> readNameExcel(InputStream inputStream, List<ReadSheet> readSheets) {
        SyncManySheetNameReadListener syncReadListener = new SyncManySheetNameReadListener();
        EasyExcel.read(inputStream).registerReadListener(syncReadListener).autoCloseStream(true)
                .build().read(readSheets).finish();
        return syncReadListener.getMap();
    }

    public static Map<Integer, List<LinkedHashMap<Integer, Object>>> readIndexExcel(InputStream inputStream, List<ReadSheet> readSheets) {
        SyncManySheetIndexReadListener syncReadListener = new SyncManySheetIndexReadListener();
        EasyExcel.read(inputStream).registerReadListener(syncReadListener).autoCloseStream(true)
                .build().read(readSheets).finish();
        return syncReadListener.getMap();
    }

    public static Map<String, List<LinkedHashMap<Integer, Object>>> readExcel(List<String> sheetNames, InputStream is) {
        Map<String, List<LinkedHashMap<Integer, Object>>> data;
        if(StringUtils.isEmpty(sheetNames)) {
            data = new HashMap<>();
            data.put("", readExcel(is));
        } else {
            List<ReadSheet> list = new ArrayList<>();
            for(String name : sheetNames) {
                list.add(new ReadSheet(null, name));
            }
            data = readNameExcel(is, list);
        }
        return data;
    }

    public static String getAsString(LinkedHashMap<Integer, Object> cell, int i) {
        Object o = cell.get(i);
        if(o == null) {
            return null;
        }
        return o.toString();
    }

    private static class SyncManySheetNameReadListener extends AnalysisEventListener<Object> {
        private Map<String, List<LinkedHashMap<Integer, Object>>> map = new HashMap<>();

        public SyncManySheetNameReadListener() { }

        public void invoke(Object object, AnalysisContext context) {
            map.computeIfAbsent(context.readSheetHolder().getSheetName(),
                    a -> new ArrayList<>()).add((LinkedHashMap<Integer, Object>) object);
        }

        public void doAfterAllAnalysed(AnalysisContext context) { }

        public Map<String, List<LinkedHashMap<Integer, Object>>> getMap() {
            return this.map;
        }

    }

    private static class SyncManySheetIndexReadListener extends AnalysisEventListener<Object> {
        private Map<Integer, List<LinkedHashMap<Integer, Object>>> map = new HashMap<>();

        public SyncManySheetIndexReadListener() { }

        public void invoke(Object object, AnalysisContext context) {
            map.computeIfAbsent(context.readSheetHolder().getSheetNo(),
                    a -> new ArrayList<>()).add((LinkedHashMap<Integer, Object>) object);
        }

        public void doAfterAllAnalysed(AnalysisContext context) { }

        public Map<Integer, List<LinkedHashMap<Integer, Object>>> getMap() {
            return this.map;
        }

    }

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D://test.xlsx");
        EasyExcelUtil.readExcel(new FileInputStream(file));

        List<Object> objects = EasyExcel.read(file).doReadAllSync();
        log.info(JSONObject.toJSONString(objects));
    }

}
